/**
 * 获取文件夹，不存在会自动创建
 * @param {Object} dirPath  目录路径
 * @param {boolean} create  不存在是否创建
 */
export async function getOrCreateDir(dirPath, create = false) {
	return new Promise(async (resolve, reject) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			fs.root.getDirectory(
				dirPath, {
					create,
				},
				function(dirEntry) {
					resolve(dirEntry)
				},
				(err) => {
					console.log(err, 'err');
					reject(err)
				}
			)
		})
	})
}

// 读取目录数据
export const getDirList = (fileNamePath) => {
	return new Promise((resolve, reject) => {
		let arr = []
		plus.io.resolveLocalFileSystemURL(
			fileNamePath,
			function(entry) {
				var directoryReader = entry.createReader()
				directoryReader.readEntries(
					function(entries) {
						for (var i = 0; i < entries.length; i++) {
							console.log('文件信息', entries[i])
							arr.push(entries[i].name)
						}
						resolve(arr)
					},
					function(e) {
						console.log('访问目录失败', e)
						resolve([])
					}
				)
			},
			function(e) {
				console.log('访问指定目录失败', e)
				resolve([])
			}
		)
	})
}


// 创建模板数据
export const createTemplateJson = async (data) => {
	return new Promise(async (resolve, reject) => {
		const dirEntry = await getOrCreateDir(
			`_doc/templateList/${data.templateId}_${data.name}`,
			true
		)
		dirEntry.getFile('templateData.json', {
			create: true
		}, (fileEntry) => {
			fileEntry.file((file) => {
				fileEntry.createWriter(
					function(writer) {
						// writer.onwritestart = function(e) {
						// 	console.log("写入数据开始");
						// }
						writer.onwrite = function(e) {
							resolve('数据写入成功')
						}
						//定位至文件结尾，即每次都是追加内容
						//writer.seek(writer.length);
						//定位至开头，即每次都是重写文件。（默认）
						//writer.seek(0);
						writer.write(JSON.stringify(data))
					},
					function(error) {
						reject(error)
					}
				)
			})
		})
	})
}


// 创建子目录
export const createSonDir = (parentEntry, sonDirName) => {
	return new Promise((resolve, reject) => {
		parentEntry.getDirectory(sonDirName, {
			create: true,
			exclusive: false
		}, function(dir) {
			console.log('创建子目录成功！', dir);
			resolve(true)
		}, function(err) {
			console.log('创建子目录成功！', err);
			reject(false)
		});
	})
}

// 创建填报数据
export const createFillJson = async (templateDirName, fillDirName, data) => {
	return new Promise(async (resolve, reject) => {
		const dirEntry = await getOrCreateDir(
			`_doc/templateList/${templateDirName}/fillList/${fillDirName}`,
			true
		)
		dirEntry.getFile('fillData.json', {
			create: true
		}, (fileEntry) => {
			fileEntry.file((file) => {
				fileEntry.createWriter(
					function(writer) {
						writer.onwrite = function(e) {
							resolve('数据写入成功')
						}
						writer.write(JSON.stringify(data))
					},
					function(error) {
						reject(error)
					}
				)
			})
		})
	})
}

// 删除文件（如果有子文件一起删除）
export const removeDir = (fliePath) => {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(
			fliePath,
			function(entry) {
				entry.removeRecursively(
					function(entry) {
						console.log('删除成功！');
						resolve(true)
					},
					function(e) {
						console.log('删除失败', e)
						reject(false)
					}
				)
			},
			function(e) {
				console.log('访问路径失败')
				reject(false)
			}
		)
	})
}
// 删除文件（如果有子文件一起删除）
export const removeFile = (fliePath) => {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(
			fliePath,
			function(entry) {
				entry.remove(
					function(entry) {
						resolve(true)
					},
					function(e) {
						console.log('删除失败', e)
						reject(false)
					}
				)
			},
			function(e) {
				console.log('访问路径失败')
				reject(false)
			}
		)
	})
}

// 创建或打开文件
//fileName 目录路径 dirEntry之前打开过的目录(没有则不填写)
export const getFileEntry = (fileName, dirEntry, create = false) => {
	return new Promise((resolve, reject) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			let entry = dirEntry || fs.root
			entry.getFile(
				fileName, {
					create,
				},
				function(fileEntry) {
					resolve(fileEntry)
				},
				function(e) {
					reject(e)
				}
			)
		})
	})
}
// 获取文件对象
export const getFile = (fileName, dirEntry) => {
	return new Promise((resolve, reject) => {
		getFileEntry(fileName, dirEntry).then((fileEntry) => {
			fileEntry.file(
				function(file) {
					file.close()
					resolve(file)
				},
				function(e) {
					file.close()
					reject('失败')
				}
			)
		})
	})
}
// 获取模板数据
export const getJsonData = async (path, dirEntry) => {
	let deffered
	let fileReader = new plus.io.FileReader()
	fileReader.onloadend = function(evt) {
		deffered(evt.target)
	}
	let file = await getFile(path, dirEntry)
	fileReader.readAsText(file, 'utf-8')
	return new Promise((resolve) => {
		deffered = resolve
	})
}
// 复制文件到指定地址
export const copyFile = async (soursePath, targetPath, fileName) => {
	return new Promise((resolve, reject) => {
		if (soursePath === `${targetPath}/${fileName}`) {
			console.log('跳过')
			resolve()
			return
		}
		plus.io.resolveLocalFileSystemURL(
			soursePath,
			(sourseEntry) => {
				plus.io.resolveLocalFileSystemURL(
					targetPath,
					(targetEntry) => {
						sourseEntry.copyTo(
							targetEntry,
							fileName,
							() => {
								resolve('复制成功')
							},
							(err) => {
								console.log(err, 'err');
								reject(err)
							}
						)
					},
					(err) => {
						console.log(err);
						reject(err)
					}
				)
			},
			(err) => {
				console.log(err);
				reject(err)
			}
		)
	})
}

// 移动文件到指定地址
export const moveFile = (soursePath, targetPath, fileName) => {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(
			soursePath,
			(sourseEntry) => {
				plus.io.resolveLocalFileSystemURL(
					targetPath,
					(targetEntry) => {
						sourseEntry.moveTo(
							targetEntry,
							fileName,
							() => {
								console.log('移动成功');
								resolve('移动成功')
							},
							(err) => {
								console.log(err, 'err');
								reject(err)
							}
						)
					},
					(err) => {
						console.log(err);
						reject(err)
					}
				)
			},
			(err) => {
				console.log(err);
				reject(err)
			}
		)
	})
}
export function renameFile(oldFilePath, newFileName) {
	plus.io.resolveLocalFileSystemURL(oldFilePath, entry => {
		entry.getParent(_oldFile => {
			entry.moveTo(_oldFile, '/' + newFileName, newFilePath => {
				console.log('newFilePath', newFilePath.fullPath)
			})
		})
	})
}

// 固定字段模糊查询设置
export const setVagueQuery = (vagueQueryData) => {
	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
		let entry = fs.root
		entry.getFile('_doc/vagueQuery.json', {
			create: true
		}, async (fileEntry) => {
			fileEntry.file((file) => {
				fileEntry.createWriter(
					function(writer) {
						writer.onwrite = function(e) {
							resolve('数据写入成功')
						}
						writer.write(JSON.stringify(vagueQueryData))
					},
					function(error) {
						reject(error)
					}
				)
			})
		})
	})
}

export const getVagueQuery = () => {
	return new Promise((resolve, reject) => {
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
			let entry = fs.root
			entry.getFile('_doc/vagueQuery.json', {
				create: true
			}, async (fileEntry) => {
				const res = await getJsonData('_doc/vagueQuery.json')
				// 获取文件数据
				if (res.result) {
					resolve(JSON.parse(res.result))
				} else {
					resolve({
						creatorList: [],
						creatorTelList: [],
						projectModelList: [],
						batchNumberList: [],
						agingAddressList: [],
					})
				}
			}, err => {
				console.log(err, 'err');
			})
		})
	})

}
// 根据图片地址判断图片是否丢失
export const checkImage = async (templateData, formData) => {
	const imageFieldIdList = templateData.fieldList.filter(item => item.type === 'upImage').map(item => item.field_id)
	let imageUrlList = []
	imageFieldIdList.forEach(item => {
		if (Array.isArray((formData[item]))) {
			imageUrlList = imageUrlList.concat(formData[item])
		}
	})
	if (imageUrlList.length === 0) return true
	const res =await checkFilesExistSync(imageUrlList.map(item => item.url))
	return res
}

/**
 * 同步检查文件是否存在（逐个检查）
 * @param {string[]} filePaths 
 * @returns {Promise<Array<{path: string, exists: boolean}>>}
 */
async function checkFilesExistSync(filePaths) {
  const results = [];
  for (const filePath of filePaths) {
    const exists = await new Promise(resolve => {
      plus.io.resolveLocalFileSystemURL(
        filePath,
        () => resolve(true),
        (err) => resolve(false)
      );
    });
	
    results.push(exists);
  }
  if (results.some(item => item === false)) {
	  return false
  }
  return true;
}